package net.lzzy.service;

import net.lzzy.entity.Comment;
import net.lzzy.repository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class ApiCommentService {

    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    private RedisTemplate redisTemplate;

    public Comment findCommentById(Integer id) {
        //"comment_api"是缓存空间的名称
        Object object = redisTemplate.opsForValue().get("comment_api"+id);
        if (object != null){
            return (Comment)object;
        }
        else {
            Optional<Comment> comment = commentRepository.findById(id);
            if (comment.isPresent()){
                redisTemplate.opsForValue().set("comment_api"+id, comment.get());
            }
            return comment.get();
        }
    }

    public void updateComment(Integer id, String content) {
        commentRepository.updateComment(id, content);
        redisTemplate.opsForValue().set("comment_api"+id, findCommentById(id));
    }

    public void deleteCommentById(Integer id) {
        commentRepository.deleteById(id);
        redisTemplate.delete("comment_api"+id);
    }
}
